package com.budingge.httpuitls;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
/**
 * URL工具类
 */
import java.net.URLDecoder;

import com.budingge.common.io.ChineseEncode;

/**
 * @author budingge.com
 *
 */
public class URLHelper {
	
	/**
	 * 注:从jsoup中提取出来的方法
	 * Get an absolute URL from a URL attribute that may be relative (i.e. an
	 * <code>&lt;a href></code> or <code>&lt;img src></code>).
	 * <p/>
	 * E.g.: <code>String absUrl = linkEl.absUrl("href");</code>
	 * <p/>
	 * If the attribute value is already absolute (i.e. it starts with a
	 * protocol, like <code>http://</code> or <code>https://</code> etc), and it
	 * successfully parses as a URL, the attribute is returned directly.
	 * Otherwise, it is treated as a URL relative to the element's
	 * {@link #baseUri}, and made absolute using that.
	 * <p/>
	 * As an alternate, you can use the {@link #attr} method with the
	 * <code>abs:</code> prefix, e.g.:
	 * <code>String absUrl = linkEl.attr("abs:href");</code>
	 * 
	 * @param attributeKey
	 *            The attribute key
	 * @return An absolute URL if one could be made, or an empty string (not
	 *         null) if the attribute was missing or could not be made
	 *         successfully into a URL.
	 * @see #attr
	 * @see java.net.URL#URL(java.net.URL, String)
	 */
	public static String absUrl(String baseUri, String relUrl) {
		URL base;
		try {
			try {
				base = new URL(baseUri);
			} catch (MalformedURLException e) {
				// the base is unsuitable, but the attribute may be abs on
				// its own, so try that
				URL abs = new URL(relUrl);
				return abs.toExternalForm();
			}
			// workaround: java resolves '//path/file + ?foo' to
			// '//path/?foo', not '//path/file?foo' as desired
			if (relUrl.startsWith("?"))
				relUrl = base.getPath() + relUrl;
			URL abs = new URL(base, relUrl);
			return abs.toExternalForm();
		} catch (MalformedURLException e) {
			return "";
		}
	}
	
	/**
	 * url特殊字符转码
	 * 
	 * @param str_url
	 * @return
	 */
	public static URL escape(URL url) {
		try {
			// 解码，防止url二次编码引起bug
			url = new URL(URLDecoder.decode(url.toExternalForm()));
			URI uri = new URI(url.getProtocol(), url.getUserInfo(),
					url.getHost(), url.getPort(), url.getPath(),
					url.getQuery(), url.getRef());
			url = uri.toURL();
			url = new URL(ChineseEncode.chineseEncoder(url.toExternalForm()));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return url;
	}


}
